<?php

namespace app\mos\controller;
use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\CardMemberAli;
use app\common\model\CardShareLog;
use app\common\model\CardShareUser;
use app\common\model\CardUserGetAli;
use app\common\model\Merchant;
use think\Controller;
use think\Session;
class Cardaliget extends Controller
{
    //领卡
    public function cardget()
    {
        //获取uid
        $template_id = request()->get('template_id');
        $acinfo=$this->getuserinfo(request()->get('auth_code'),$template_id);
        $params['access_token']=$acinfo['access_token'];
        $params['template_id']=request()->get('template_id');
        $params['request_id']=request()->get('request_id');
        $arr = request()->param();
//        var_dump($arr);
//        exit();
        $content = $this->activateform_query($params);
        $params2=$params;
        $params2['uid']=$acinfo['user_id'];
        $params2['infos']=json_decode($content['data']['infos'],true);
        $params2['template_id'] = request()->get('template_id');
        $card= $this->card_open($params2);
        $card = $card['alipay_marketing_card_open_response'];
//        file_put_contents('/data2/html/payos/test.txt', 'ali-4' . json_encode($card), FILE_APPEND);
        if ($card['code'] == 10000) {
            $CardMemberAli = new CardMemberAli();
            $cardinfo = $card['card_info'];
            $cardus = $CardMemberAli->where(['template_id'=>$template_id])->field('mid,top_mid,card_type')->find();
            $CardGetAli = new CardUserGetAli();
            $data['mid'] = $cardus['mid'];
            $data['top_mid'] = $cardus['top_mid'];
            $data['user_id'] = $acinfo['user_id'];
            $data['code'] = $cardinfo['biz_card_no'];
            $data['external_card_no'] = $cardinfo['external_card_no'];
            $data['template_id'] = $template_id;
            $data['card_type'] = $cardus['card_type'];
            $data['userinfo'] = json_encode($acinfo,JSON_UNESCAPED_UNICODE);
            $data['have'] = 1;
            $data['fireinfo'] = json_encode($content, JSON_UNESCAPED_UNICODE);
            $data['open'] = json_encode($card, JSON_UNESCAPED_UNICODE);
            $data['open_date'] = $cardinfo['open_date'];
            $data['valid_date'] = $cardinfo['valid_date'];
            $data['create_time'] = time();
            if (isset($arr['share_uid'])){
                $data['outerstr'] = 'SHARE|'.$arr['share_uid'];
            }
            if (isset($arr['mid'])){
                $data['outerstr'] = 'MID|'.$arr['mid'];
            }
            $CardGetAli->allowField(true)->save($data);
            //有分享行为则转向分享记录
            if (isset($arr['share_uid'])){
                $arrs['get_user_id'] = $acinfo['user_id'];
                $arrs['get_code'] = $cardinfo['biz_card_no'];
                $arrs['share_uid'] = $arr['share_uid'];
                $arrs['template_id'] = $arr['template_id'];
//                var_dump($arrs);
//                exit();
                $this->shareget($arrs);
            }
            $this->redirect('Carduserali/index',['mid' => $cardus['mid']]);
        }

    }

    //分享领取
    private function shareget($arr){
        $CardShareUser = new CardShareUser();
        $CardShareLog = new CardShareLog();
        $shareuser = $CardShareUser->where(['user_id'=>$arr['share_uid']])->find();
        if ($shareuser){
            $CardShareUser->where(['user_id'=>$arr['share_uid']])->setInc('get_ren');
            $data['top_mid'] = $shareuser['top_mid'];
            $data['mid'] = $shareuser['mid'];
            $data['user_id'] = $shareuser['user_id'];
            $data['get_user_id'] = $arr['get_user_id'];
            $data['get_code'] = $arr['get_code'];
            $data['template_id'] = $arr['template_id'];
            $data['share_uid'] = $shareuser['id'];
            $data['create_time'] = time();
            $CardShareLog->allowField(true)->save($data);
        }
    }

    //开卡
    public function card_open($param){
        //初始化
        $datas['merchid'] = $this->get_mid($param['template_id']);
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        //参数
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.open";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['auth_token']=$param['access_token'];
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_serial_no' => date('YmdHis').rand(10000,99999),
            'card_template_id'=>$param['template_id'],
            'card_user_info'=>array(
                'user_uni_id'=>$param['uid'],
                'user_uni_id_type'=>"UID",
            ),
            'card_ext_info'=>array(
                'external_card_no'=>date('Ymdhis').rand(1000,9999),
                'open_date'=>date('Y-m-d H:i:s'),
                'valid_date'=>"2020-12-12 23:59:59",
                'level'=>'VIP1',
                'point'=>'10',
                'balance'=>'8.88',
            ),
//            'member_ext_info'=>array(
//                'name'=>$param['infos'][1]['OPEN_FORM_FIELD_NAME'],
//                'cell'=>$param['infos'][0]['OPEN_FORM_FIELD_MOBILE'],
//            ),

        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
//return $data;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        return $content;
    }

    //查询用户提交的会员卡表单信息
    public function activateform_query($param)
    {
        //初始化
        $datas['merchid'] = $this->get_mid($param['template_id']);
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        //参数
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateform.query";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['auth_token']=$param['access_token'];
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'biz_type' => "MEMBER_CARD",
            'template_id' => $param['template_id'],
            "request_id" => $param['request_id'],
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        if($content['alipay_marketing_card_activateform_query_response']['code']==10000){
            $info['code']=0;
            $info['data']['infos']=$content['alipay_marketing_card_activateform_query_response']['infos'];
        }else{
            $info['code']=$content['alipay_marketing_card_activateform_query_response']['code'];
            $info['message']=$content['alipay_marketing_card_activateform_query_response']['msg'];
        }
        return $info;
    }

    //获取用户userid
    public function getuserinfo($code="e2691129a3424fa696921ac1a56fRX10",$template_id){
        //初始化
        $datas['merchid'] = $this->get_mid($template_id);
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        //参数
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.system.oauth.token";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['app_auth_token'] = $users['ali_merid'];
        $data['grant_type'] = 'authorization_code';
        $data['code'] = $code;
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $uid = $aliObj->getuid($data);
        $user = json_decode($uid, true);
        $params['user_id']=$user['alipay_system_oauth_token_response']['user_id'];
        $params['access_token']=$user['alipay_system_oauth_token_response']['access_token'];
        $params['data'] = $user;
//        $params['nickname'] = $user['alipay_system_oauth_token_response']['nick_name'];
        return $params;

    }

    //获取mid 通过tempalte_id
    private function get_mid($template_id){
        //获取mid
        $CardMemberAli = new CardMemberAli();
        $merchid = $CardMemberAli->where(array('template_id'=>$template_id))->value('mid');
        return $merchid;
    }

}
